import Request from '@/utils/request.js'
import { getToken, setToken, removeToken, saveUserInfo, loadUserinfo } from '@/utils/ProjectTools.js'
import {http} from "@/api";
import store from "@/store";


// 重置用户令牌和角色信息
const state = {
    userInfo: loadUserinfo(),
    token: getToken(),
    valid: false, // 当前路由是否有效
    roles: {}, //角色信息
    menuList: [],
}



const mutations = {
    SET_USERINFO: (state, data) => {
        saveUserInfo(data)
        state.userInfo = data
    },
    SET_TOKEN: (state, token) => {
        setToken(token)
        state.token = token
    },
    LOGOUT(state) {
        removeToken();
        state.tenantId = null
        state.userInfo = {};
        state.token = '';
        state.valid = false;
        state.roles = null;
    },
    SET_MENUS: (state, data) => {
        state.menuList = data;
    },
};

const actions = {
    // 用户登录
    login({ commit, dispatch }, userInfo) {
        const { username, password } = userInfo
        return new Promise(async (resolve, reject) => {
          http.login({ username, password }).then(res => {
              commit('SET_USERINFO', res.data);
              commit('SET_TOKEN', res.data.id);
              resolve()
          }).catch(() => {
            reject()
          })
        })
    },
    getUserInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            http.user.getUserInfo(state.userInfo.id).then(res => {
                commit('SET_MENUS', res.data.menuList)
                commit('SET_USERINFO', res.data);
                resolve(res.data.menuList)
            }).catch(() => {
                reject()
            })
        })
    },
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('LOGOUT')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
